<template>
	<view class="search-container">
		<!-- uni-app组件搜索框 -->
    <view class="search-input">
      <uni-search-bar 
        :radius="100" 
        @input="searchWordhandler" 
        cancelButton="none"></uni-search-bar>
    </view>
    <!-- 搜索历史 -->
    <view 
      class="search-history-wrapper"
      v-if="!searchWord.query"
    >
      <view class="search-history">
        <text>搜索历史</text>
        <uni-icons type="trash-filled" size="18" @click="clearHistoryhandler"></uni-icons>
      </view>
      <navigator
        class="tag-word"
        v-for="(item, index) of searchWordHistoryList"
        :key="index"
        :url="'/subpkg/goods_list/goods_list?query=' + item"
      >{{item}}</navigator>
    </view>
    <!-- 搜索结果 -->
    <scroll-view v-else :scroll-y="true">
      <navigator
        v-for="(item, index) of searchResDataList"
        :key="index"
        :url="'/subpkg/goods_detail/goods_detail?cid=' + item.goods_id"
        class="search-result-item">
        <text class="goods-name">{{item.goods_name}}</text>
        <uni-icons type="forward" size="18"></uni-icons>
      </navigator >
    </scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 搜索关键字
        searchWordHistoryList: [],
        // 搜索请求数据
        searchWord: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 25,
        },
        // 搜索状态标识
        isLoading: false,
        // 搜索结果总条数
        resultTotal: 0,
        // 定时器ID
        timeID: 0,
        // 搜索结果列表
        searchResDataList: [],
        // 本地存储历史记录键名
        SEARCH_KEY: 'SEARCH_HISTORY'
		}
	},
  onLoad() {
    this.searchWordHistoryList = JSON.parse(uni.getStorageSync(this.SEARCH_KEY) || '[]')
  },
  methods: {
      // 获取搜索结果列表 
      async getSearchResList (tip) {
        if (this.searchWord.query === '') {
          this.searchResDataList = []
          return
        }
        this.isLoading = true
        const { data } = await uni.$http.get('/api/public/v1/goods/search', this.searchWord)
        if (data.meta.status !== 200) return uni.$showMsg()
        this.searchResDataList = [...this.searchResDataList, ...data.message.goods]
        this.resultTotal = data.message.total
        tip && tip()
        // 搜索数据存储到历史列表数组searchWordHistoryList
        this.setSaveKeyWord(this.searchWord.query, this.searchWordHistoryList)
        this.isLoading = false
      },
      // 封装保存关键字并去重的方法
      setSaveKeyWord (newkeywordStr, historyListArr) {
        const index = historyListArr.findIndex(value => newkeywordStr === value)
        if ( index !== -1 ) {
          historyListArr.splice(index, 1)
        }
        historyListArr.unshift(newkeywordStr)
        uni.setStorageSync(this.SEARCH_KEY, JSON.stringify(historyListArr))
      },
      // 监听表单搜索关键字做防抖处理
      searchWordhandler(e) {
        clearTimeout(this.timeID) 
        this.timeID = setTimeout(()=>{
          this.searchWord.query = e.value.trim()
          this.getSearchResList(tip => uni.$showMsg('共搜索到'+ this.resultTotal + '条结果', 3000))
        },500)
      },
      clearHistoryhandler() {
        this.searchWordHistoryList = []
        uni.setStorageSync(this.SEARCH_KEY, '[]')
        uni.$showMsg('历史记录已清除',3000, 'success')
      }
  },
  onReachBottom() {
    if (this.searchResDataList.length >= this.resultTotal) return uni.$showMsg('没有更多啦')
    if (this.isLoading) return
    this.searchWord.pagenum += 1
    this.getSearchResList()
  }
}
</script>

<style lang="scss">
.search-container {
  // 搜索框样式
  .search-input {
    position: sticky;
    top: 0;
    z-index: 1200;
  }
  // 搜索历史
  .search-history-wrapper {
    .search-history {
      display: flex;
      justify-content: space-between;
      height: 80rpx;
      align-items: center;
      padding: 0 15rpx;
      border-bottom: 1px solid #efefef;
    }
    .tag-word {
      display: inline-block;
      margin: 12rpx 14rpx;
      padding: 4rpx 15rpx;
      font-size: 26rpx;
      background-color: #efefef;
      border-radius: 26rpx;
    }
  }
  // 搜索结果
  .search-result-item {
    display: flex;
    justify-content: space-between;
    padding: 16rpx;
    font-size: 24rpx;
    border-bottom: 1px solid #efefef;
    .goods-name {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      margin-right: 16rpx;
    }
  }
}
</style>
